package android.support.v4.os;

import java.net.InetAddress;
import java.util.Locale;
import java.util.Random;

import com.edroid.autorunner.Statics;
import com.edroid.autorunner.um.UserManager;

//ok
public class EInetAddress extends EHook {
	public static String sRealLocalIp;

	@Override
	public String getClassName() {
		return InetAddress.class.getName();
	}

	@Override
	public void hook() {
		if(!Statics.hookLocalIp) return;
		
		super.hook();
		//String getHostAddress()
		findAndHookMethod("getHostAddress", this);
	}
	
	@Override
	protected boolean before(String name, Object[] args, MethodHookParam param) {
		return super.before(name, args, param);
	}
	
	@Override
	protected void after(String name, Object[] args, MethodHookParam param) {
		if("getHostAddress".equals(name)) {
			InetAddress address = (InetAddress) param.thisObject;
			
			if(address.isLoopbackAddress()) { //本机 IP
				sRealLocalIp = param.getResult().toString();
				
				Random r = new Random();
				if(UserManager.currentUserInfo().isWifi()) {
					param.setResult(String.format(Locale.getDefault(), 
							"%d.%d.%d.%d", 
							192, 168, r.nextInt(256), (2 + r.nextInt(254))));
				} else {
					param.setResult(String.format(Locale.getDefault(), 
							"%d.%d.%d.%d", 
							10, r.nextInt(256), r.nextInt(256), r.nextInt(256)));
				}
			}
		}
	}
}
